package com.ruoyi.system.controller;


import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.CapitalAccount;
import com.ruoyi.system.domain.vo.CapitalAccountVO;
import com.ruoyi.system.service.CapitalAccountService;

import com.ruoyi.system.utils.CapitalAccountExcelParser;
import com.ruoyi.system.utils.ExcelParseError;
import com.ruoyi.system.utils.ExcelParseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.util.List;


/**
 * @author : 王孟轩
 * @date : 2025/2/24 22:07
 * @description :
 **/
@RestController
@RequestMapping("/account")
public class CapitalAccountController {

    @Autowired
    private CapitalAccountService capitalAccountService;

    /**账户列表*/
    @PostMapping("/list")
    @RequiresPermissions("system:account:list")
    public AjaxResult CapitalAccountList(@RequestBody CapitalAccountVO capitalAccountVO){

        return capitalAccountService.CapitalAccountList(capitalAccountVO);
    }
    /**添加账户*/
    @PostMapping("/add")
    @RequiresPermissions("system:account:add")
    public AjaxResult CapitalAccountAdd(@RequestBody CapitalAccountVO capitalAccountVO){

        return capitalAccountService.CapitalAccountAdd(capitalAccountVO);
    }
    /**账户修改*/
    @PostMapping("/update")
    @RequiresPermissions("system:account:update")
    public AjaxResult CapitalAccountUpdate(@RequestBody CapitalAccountVO capitalAccountVO){
        System.out.println(11111);
        return capitalAccountService.CapitalAccountUpdate(capitalAccountVO);
    }


    /**
     * 添加回显编号
     * */
    @GetMapping("/number")
    @RequiresPermissions("system:account:number")
    public AjaxResult number(@RequestParam int accountSort){
        return capitalAccountService.number(accountSort);
    }

    /**
     * 导出模版
     * */
    @PostMapping("/downloadExcelTemplate")
    public ResponseEntity<Resource> downloadExcelTemplate() {
        try {
            // 加载模板文件
            Resource resource = new ClassPathResource("/AccountTemplate.xlsx");

            // 检查文件是否存在
            if (!resource.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=voucher_data.xls");

            // 返回文件流
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentLength(resource.contentLength())
                    .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                    .body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

//    @RequiresPermissions("system:account:importExcel")
//    @PostMapping("/importExcel")
//    public AjaxResult importExcel(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<CapitalAccount> util = new ExcelUtil<CapitalAccount>(CapitalAccount.class);
//        List<CapitalAccount> List = util.importExcel(file.getInputStream());
//        System.out.println(List);
//
//
//        return  capitalAccountService.importUser(List);
//    }
    @Autowired
    CapitalAccountExcelParser capitalAccountExcelParser;
    @RequiresPermissions("system:account:importExcel")
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file,boolean updateSupport) {
        try {
            // 调用工具类解析 Excel
            ExcelParseResult<CapitalAccount> result = capitalAccountExcelParser.parse(file);

            // 处理解析结果
            List<CapitalAccount> accounts = result.getData();
            List<ExcelParseError> errors = result.getErrors();
            capitalAccountService.CapitalAccountAddBatch(accounts);
            // 打印成功数据
            System.out.println("成功解析数据：" + accounts.size() + " 条");
            accounts.forEach(account -> System.out.println(
                    "ID: " + account.getId() +
                            ", 编码: " + account.getAccountCoding() +
                            ", 名称: " + account.getAccountTitle()
            ));

            // 打印错误信息
            if (!errors.isEmpty()) {
                System.out.println("解析失败行数：" + errors.size());
                errors.forEach(error -> System.out.println(
                        "第" + error.getRowIndex() + "行错误：" + error.getMessage()
                ));
            }

            return AjaxResult.success("上传完成，成功：" + accounts.size() + " 条，失败：" + errors.size() + " 条",errors) ;
        } catch (IOException e) {
            return AjaxResult.error("文件解析失败：" + e.getMessage());
        }
    }
}
